package com.wzh.prac.lucene01;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.*;
import java.nio.file.Paths;

/**
 * Created with IntelliJ IDEA.
 * User: wzh
 * Date: 2016/2/24
 * Time: 13:16
 */
public class Indexer {

    private IndexWriter writer ;

    /**
     * 构造函数
     * @param indexDir
     * @throws IOException
     */
    public Indexer(String indexDir) throws IOException {
        Directory dir = FSDirectory.open(Paths.get(indexDir));
        Analyzer analyzer = new StandardAnalyzer();//标准分词器
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        writer = new IndexWriter(dir,config);
    }

    /**
     * 关闭写索引
     * @throws IOException
     */
    public void close() throws IOException {
        writer.close();
    }

    public int index(String dataDir) throws IOException {
        if(new File(dataDir).isDirectory()){
            File[] files = new File(dataDir).listFiles();
            for(File temp :files){
                indexFile(temp);
            }
        }else{
            System.out.println("请输入正确的文件夹路径...");
        }

        return writer.numDocs();
    }

    public void indexFile(File file) throws IOException {
        System.out.println("当前正在索引的文件为:"+file.getCanonicalPath());
        Document doc = getDocument(file);
        writer.addDocument(doc);
    }

    private Document getDocument(File file) throws IOException {
        Document doc = new Document();
        doc.add(new TextField("content",readFileContent(file), Field.Store.YES));
        doc.add(new TextField("fileName", file.getName(), Field.Store.YES));
        doc.add(new TextField("fullPath", file.getCanonicalPath(), Field.Store.YES));
        return doc;
    }

    private String readFileContent(File file){
        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result = result+s;
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String indexDir = "F:\\index";
        String dataDir ="F:\\lucene_data";
        Indexer indexer = null;
        int numIndexed = 0;
        long start = System.currentTimeMillis();
        try {
           indexer =  new Indexer(indexDir);
           numIndexed = indexer.index(dataDir);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (indexer != null) {
                try {
                    indexer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("索引的文件为："+numIndexed+"个 》》  花费时间为："+(end-start)+" ms ");
    }


}
